package pf.springBoot.springBootSSO.interceptor;

//package com.xunyji.springboot_login_session.interceptor;

//import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import pf.java.pfHelper.PFAllowAnonymous;
import pf.java.pfHelper.config.PFDataHelper;
//import pf.springBoot.springBootMetabaseLogin.model.SystemUser;
import pf.java.pfHelper.model.SystemUser;
import pf.springBoot.springBootSSO.oAuth.FormsAuth;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 王杨帅
 * @create 2018-09-11 21:31
 * @desc 登录状态拦截器
 **/
//@Slf4j
public class UserAuthorizeAttribute//LoginInterceptor 
implements HandlerInterceptor {
    public Boolean IsLogin = false;
////原版
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//			
//        //log.info("==========登录状态拦截");
//
//        HttpSession session = request.getSession();
//        //log.info("sessionId为：" + session.getId());
//
//        // 获取用户信息，如果没有用户信息直接返回提示信息
//        Object userInfo = session.getAttribute("userInfo");
//        if (userInfo == null) {
//            //log.info("没有登录");
//            response.getWriter().write("Please Login In");
//            return false;
//        } else {
//            //log.info("已经登录过啦，用户信息为：" + session.getAttribute("userInfo"));
//        }
//
//        return true;
//    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Boolean Pass = false;
        try
        {
            //var userData = FormsAuth.GetUserData();
            //if (userData == null || string.IsNullOrWhiteSpace(userData.UserCode))
            if (!IsLogined())
            {

                HandlerMethod handlerMethod = (HandlerMethod) handler;
                // 获取方法上的注解
                PFAllowAnonymous requiredPermission = handlerMethod.getMethod().getAnnotation(PFAllowAnonymous.class);
                // 如果方法上的注解为空 则获取类的注解
                if (requiredPermission == null) {
                    requiredPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(PFAllowAnonymous.class);
                }

                if (requiredPermission != null){
                	return true;
                }                
                
            	//response.getWriter().write("Please Login In<a href='/User/Login'>转到登陆页</a>");
            	//response.encodeRedirectUrl("/User/Login");
//            	response.sendRedirect("/User/Login");
            	response.sendRedirect("/User/LoginMetabase");
            	//return true;//https://bbs.csdn.net/topics/392423903
            	//直接重定向到登录页面
                //response.sendRedirect(request.getContextPath()+"/User/Login");
            	
//                httpContext.Response.StatusCode = 401;//无权限状态码
//                Pass = false;
//                IsLogin = false;
            }else
            {
//                //var userCache = Caching.Get(userData.UserCode) as SystemUser;//因为系统用到cache,所以cache丢失的话,也要求重新登陆
//                var userCache = FormsAuth.GetUserExData<SystemUser>();
//                if (userCache == null)
//                {
//                    httpContext.Response.StatusCode = 401;//无权限状态码
//                    Pass = false;
//                    IsLogin = false;
//                }
//                else
//                {
                    Pass = true;
                    IsLogin = true;
//                }
            }
        }
        catch (Exception e)
        {
            return Pass;
        }
        return Pass;
        
//        //log.info("==========登录状态拦截");
//
//        HttpSession session = request.getSession();
//        //log.info("sessionId为：" + session.getId());
//
//        // 获取用户信息，如果没有用户信息直接返回提示信息
//        Object userInfo = session.getAttribute("userInfo");
//        if (userInfo == null) {
//            //log.info("没有登录");
//            response.getWriter().write("Please Login In");
//            return false;
//        } else {
//            //log.info("已经登录过啦，用户信息为：" + session.getAttribute("userInfo"));
//        }
//
//        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
    /// <summary>
    /// 已登陆
    /// </summary>
    /// <returns></returns>
    public static Boolean IsLogined()
    {
        //var userData = FormsAuth.GetUserData();
    	SystemUser userData = FormsAuth.GetUserExData(SystemUser.class);
        return !(userData == null || PFDataHelper.StringIsNullOrWhiteSpace(userData.UserCode));
    }
}
